from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.decorators import action
from rest_framework.filters import OrderingFilter
from rest_framework.response import Response
from rest_framework import mixins, viewsets, status
from rest_framework.viewsets import GenericViewSet

from utils.common import Pagination
from apps.club_system.club.models import ClubType, Log
from apps.club_system.club.serializers.club_type import ClubTypeserializer, ClubTypeListserializer


class ClubTypeViewSet(mixins.CreateModelMixin,
                      mixins.RetrieveModelMixin,
                      mixins.UpdateModelMixin,
                      mixins.ListModelMixin,
                      GenericViewSet):
    """社团分类表视图"""
    queryset = ClubType.objects.all().order_by('id')
    serializer_class = ClubTypeserializer
    filter_backends = (OrderingFilter, DjangoFilterBackend)
    pagination_class = Pagination
    ordering_fields = ('id', 'created_time')
    filter_fields = ['is_active']

    def create(self, request, *args, **kwargs):
        if not request.user.is_admin() and not request.user.is_role('club_school_manager'):
            return Response({'message': '您无权限进行新增！'}, status=status.HTTP_400_BAD_REQUEST)
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        Log.objects.create(username=request.user.username, name=request.user.realname, operate_type=1,
                           table_name='ClubType', comment=f'新增了社团分类',
                           detail=str(request.data) if request.data else '')
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def update(self, request, *args, **kwargs):
        if not request.user.is_admin() and not request.user.is_role('club_school_manager'):
            return Response({'message': '您无权限进行修改！'}, status=status.HTTP_400_BAD_REQUEST)
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)

        if getattr(instance, '_prefetched_objects_cache', None):
            # If 'prefetch_related' has been applied to a queryset, we need to
            # forcibly invalidate the prefetch cache on the instance.
            instance._prefetched_objects_cache = {}
        Log.objects.create(username=request.user.username, name=request.user.realname, operate_type=2,
                           table_name='ClubType', comment=f'新增了社团分类',
                           detail=str(request.data) if request.data else '')
        return Response(serializer.data)

    @action(methods=['get'], detail=False, url_path='is_active')
    def get_club_type(self, request):
        queryset = ClubType.objects.filter(is_active=True)
        serializer = ClubTypeserializer(queryset, many=True)
        return Response(serializer.data)

